﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using BaseLib.FileHelper;
using System.Drawing.Drawing2D;
using Microsoft.Win32;

namespace SSTrafficStatistics
{
    public partial class Form1 : Form
    {
        private const string Version = "V1.1";

        private static string iniPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cfg.ini");

        public Form1()
        {
            InitializeComponent();
            dtpExpiration.MinDate = DateTime.Now;
            tmrInterval.Enabled = true;
        }

        private void btHandle_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string strUri = IniOperator.ReadString("JustMySocks", "Uri", "https://justmysocks3.net/members/getbwcounter.php?service=335412&id=da0e8ffc-5d09-4fd7-896b-bba6fa1f66c6", iniPath);

                if (!Uri.IsWellFormedUriString(strUri, UriKind.RelativeOrAbsolute))
                {
                    niUsed.ShowBalloonTip(3000, "Just My Socks 用量", $"无效的Uri", ToolTipIcon.Error);
                    return;
                }

                Uri uri = new Uri(strUri);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                string ret = string.Empty;
                using (StreamReader rd = new StreamReader(request.GetResponse().GetResponseStream()))
                {
                    ret = rd.ReadToEnd();
                    rd.Close();
                }
                Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(ret);
                if (dict.Equals(null) || dict.Count != 3)
                {
                    niUsed.ShowBalloonTip(3000, "Just My Socks 用量", $"查询结果错误", ToolTipIcon.Error);
                    return;
                }

                if (!dict.TryGetValue("monthly_bw_limit_b", out object total) ||
                    !dict.TryGetValue("bw_counter_b", out object cur) ||
                    !dict.TryGetValue("bw_reset_day_of_month", out object next))
                {
                    niUsed.ShowBalloonTip(3000, "Just My Socks 用量", $"查询结果解析错误", ToolTipIcon.Error);
                    return;
                }

                double dTotal = Convert.ToDouble(total);
                double dCur = Convert.ToDouble(cur);
                int iNext = Convert.ToInt32(next);
                DateTime dtNext = new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, iNext);
                int iDays = (int)dtNext.Subtract(DateTime.Now).TotalDays;
                string strExpirationDate = IniOperator.ReadString("JustMySocks", "Expiration", dtNext.ToString("yyyy-MM-dd"), iniPath);
                if (!DateTime.TryParse(strExpirationDate, out DateTime dtExpiration))
                {
                    dtExpiration = dtNext;
                }
                int iExpirationDays = (int)dtExpiration.Subtract(DateTime.Now).TotalDays;

                string info = $"当前用量：{dCur / (1000 * 1000 * 1000):f4} GB（{dCur / dTotal * 100:f4}%）\r\n" +
                    $"订阅流量：{dTotal / (1000 * 1000 * 1000):f4} GB\r\n" +
                    $"重置日期：{dtNext.ToString("yyyy-MM-dd")}（{iDays}天）\r\n" +
                    $"有效期至：{dtExpiration.ToString("yyyy-MM-dd")}（{iExpirationDays}天）";
                niUsed.ShowBalloonTip(3000, "Just My Socks 用量", info, ToolTipIcon.None);
            }
            catch (Exception ex)
            {
                niUsed.ShowBalloonTip(3000, "Just My Socks 用量", $"查询错误:{ex.Message}", ToolTipIcon.Error);
            }
            finally
            {
                查询ToolStripMenuItem.Enabled = true;
            }
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadConfig();
            this.ShowInTaskbar = true;
            this.Visible = true;
        }

        private void 查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!btHandle.IsBusy)
            {
                btHandle.RunWorkerAsync();
            }
        }

        private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.SaveConfig())
            {
                this.ShowInTaskbar = false;
                this.Visible = false;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            this.ShowInTaskbar = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Visible = false;
            this.ShowInTaskbar = false;
            this.Text = this.Text + " " + Version;
            this.versionToolStripMenuItem.Text = Version;
            LoadConfig();
        }

        private void LoadConfig()
        {
            if (!File.Exists(iniPath))
            {
                SaveConfig();
            }

            txtUri.Text = IniOperator.ReadString("JustMySocks", "Uri", "https://justmysocks3.net/members/getbwcounter.php?service=335412&id=da0e8ffc-5d09-4fd7-896b-bba6fa1f66c6", iniPath);
            string strExpirationDate = IniOperator.ReadString("JustMySocks", "Expiration", DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd"), iniPath);
            if (!DateTime.TryParse(strExpirationDate, out DateTime dtExpiration))
            {
                dtExpiration = DateTime.Now.AddMonths(1);
            }
            dtpExpiration.Value = dtExpiration;

            string strTipIntervalHours = IniOperator.ReadString("JustMySocks", "TipInterval", "1", iniPath);
            if (!double.TryParse(strExpirationDate, out double dTipInterval))
            {
                dTipInterval = 1;
            }
            nudTipInterval.Value = Convert.ToDecimal(dTipInterval);
            chkTipEnable.Checked = IniOperator.ReadBoolean("JustMySocks", "TipEnable", true, iniPath);

            #region 获取注册表是否设置了开机启动
            RegistryKey currenUser = Registry.CurrentUser;
            RegistryKey run = currenUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            string valName = AppDomain.CurrentDomain.FriendlyName.ToLower().Replace(".exe", "");

            if (run == null || run.GetValue(valName) == null)
            {
                chkAutoStart.Checked = false;
            }
            else
            {
                chkAutoStart.Checked = true;
            }

            run?.Close();
            currenUser?.Close();
            #endregion
        }

        private bool SaveConfig()
        {
            if (!Uri.IsWellFormedUriString(txtUri.Text, UriKind.RelativeOrAbsolute))
            {
                niUsed.ShowBalloonTip(3000, "Just My Socks 用量", $"无效的Uri", ToolTipIcon.Error);
                return false;
            }
            IniOperator.WriteString("JustMySocks", "Uri", txtUri.Text, iniPath);
            IniOperator.WriteString("JustMySocks", "Expiration", dtpExpiration.Value.ToString("yyyy-MM-dd"), iniPath);
            IniOperator.WriteString("JustMySocks", "TipInterval", Convert.ToString(nudTipInterval.Value), iniPath);
            IniOperator.WriteBoolean("JustMySocks", "TipEnable", chkTipEnable.Checked, iniPath);

            #region 写入配置的开机启动信息到注册表
            RegistryKey currenUser = Registry.CurrentUser;
            RegistryKey run = currenUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            string valName = AppDomain.CurrentDomain.FriendlyName.ToLower().Replace(".exe", "");
            if (run == null)
            {
                return false;
            }

            if (this.chkAutoStart.Checked)
            {
                run.SetValue(valName, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName));
            }
            else
            {
                run.DeleteValue(valName);
            }
            run?.Close();
            currenUser?.Close();
            #endregion

            this.tmrInterval.Stop();
            if (!this.chkTipEnable.Checked)
            {
                return true;
            }
            this.tmrInterval.Interval = (int)(Convert.ToDouble(this.nudTipInterval.Value) * 60 * 60 * 1000);
            

            return true;
        }

        private void chkAutoStart_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkAutoStart.Checked)
            {
                this.chkAutoStart.BackColor = Color.FromArgb(128, 255, 128);
            }
            else
            {
                this.chkAutoStart.BackColor = Color.FromArgb(255, 128, 128);
            }
        }

        private void chkTipEnable_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkTipEnable.Checked)
            {
                this.chkTipEnable.BackColor = Color.FromArgb(128, 255, 128);
            }
            else
            {
                this.chkTipEnable.BackColor = Color.FromArgb(255, 128, 128);
            }
        }

        private void tmrInterval_Tick(object sender, EventArgs e)
        {
            tmrInterval.Stop();
            查询ToolStripMenuItem.PerformClick();
        }

        private void btHandle_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!this.chkTipEnable.Checked)
            {
                return;
            }
            tmrInterval.Interval = (int)(Convert.ToDouble(this.nudTipInterval.Value) * 60 * 60 * 1000);
            tmrInterval.Start();
        }
    }
}
